package com.example.springbootsenior.vaildated.controller;

import com.example.springbootsenior.vaildated.entry.User;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.ConstraintViolation;
import javax.validation.Valid;
import javax.validation.Validation;
import java.util.Set;

/**
 * 功能描述:
 *
 * @author: 李明杰
 * @date: 2021/12/9 10:10
 */
@RestController
public class ValidationController {
    /**
     * 校验不通过时直接抛异常
     *
     * @param user
     * @return
     */
    @PostMapping("/Valid1")
    public Object test1(@Valid User user) {
        System.err.println(user);
        return "操作成功！";
    }

    /**
     * 将校验结果放进BindingResult里面，用户自行判断并处理
     *
     * @param user
     * @param bindingResult
     * @return
     */
    @PostMapping("/Valid2")
    public Object test2(@Valid User user, BindingResult bindingResult) {
        // 参数校验
        if (bindingResult.hasErrors()) {
            String messages = bindingResult.getAllErrors()
                    .stream()
                    .map(ObjectError::getDefaultMessage)
                    .reduce((m1, m2) -> m1 + "；" + m2)
                    .orElse("参数输入有误！");
            throw new IllegalArgumentException(messages);
        }

        return "操作成功！";
    }

    /**
     * 用户手动调用对应API执行校验
     *
     * @param user
     * @return
     */
    @PostMapping("/Valid3")
    public Object test3(@RequestBody User user) {
        // 参数校验
        validate(user);

        return "操作成功！";
    }

    private void validate(@Valid User user) {
        Set<ConstraintViolation<@Valid User>> validateSet = Validation.buildDefaultValidatorFactory()
                .getValidator()
                .validate(user, new Class[0]);
        if (!CollectionUtils.isEmpty(validateSet)) {
            String messages = validateSet.stream()
                    .map(ConstraintViolation::getMessage)
                    .reduce((m1, m2) -> m1 + "；" + m2)
                    .orElse("参数输入有误！");
            throw new IllegalArgumentException(messages);

        }
    }
}
